# @File     : spider_weather.py
# @function : 输入城市名北京，在文件中查找城市编码，通过编码获得url，爬取页面的天气预报
# @Software : PyCharm Community Edition
# @Knowledge: BeautifulSoup、正则表达式
from typing import List, Any

from bs4 import BeautifulSoup
import re
import requests
import sys  # 用于sys.exit()


# 根据输入的城市名从city.txt文件中获取对应的城市编号，最终返回城市编号
def gain_city_code():
    # 补全代码：在控制台输入城市名，根据输入的城市名从city.txt文件中获取对应的城市编号，最终返回城市编号
    city = input('请输入城市名称：') or '北京'
    pattern=re.compile(r'\d+='+city,re.S)
    with open("city.txt","r",encoding="utf-8") as f:
        content=f.read()
        citycode=re.findall(pattern,content)
        if not citycode:
            print("error city code")
        else:
            #print(citycode)
            return citycode[0].split("=")[0]


# 根据城市编号，爬取对应城市的天气网页，最终将天气信息在控制台打印输出。
def show_weather(city_code):
    # 访问网页的地址
    url = "http://localhost:8080/weather/" + city_code + '.html'
    response = requests.get(url)
    if response.status_code == 200:
        content=BeautifulSoup(response.content.decode("utf-8"),'html.parser')
        body=content.find("div",{"id":"7d"},class_="c7d")

        weather_li=body.ul.find_all("li")
        days=[]
        tempH=[]
        tempL=[]
        wind=[]
        weather=[]
        for li in weather_li:
            days.append(li.h1.string)
            p=li.findAll("p")
            weather.append(p[0].string)
           # win=li.find("p",class_="win")
            wind.append(p[2].em.span['title']+p[2].i.string)
            if p[1].span.string is not None:
                tempH.append(p[1].span.string)
            else:
                tempH.append("None")
            tempL.append(p[1].i.string)

        result=list(zip(days,tempH,tempL,wind,weather))
        for i in result:
            print(i)
        return result




        pass

    else:
        print(f"error code:{response.status_code}")


if __name__ == "__main__":
    code = gain_city_code()
    show_weather(code)
